# 引入mqtt包
import paho.mqtt.client as mqtt
# 使用独立线程运行
from threading import Thread
from multiprocessing import Process, Queue
import serial  # 导入串口包
import time
import threading
from threading import RLock
import re
import binascii
import numpy as np
import json
lock = RLock()
ser = serial.Serial("COM10", 38400, timeout=1)  # 设置串口数据
def ser_receive():
    while True:
        try:
            lock.acquire()
            ser.flushInput()  # 清除串口缓存数据
            time.sleep(3)
            # s=ser.readline()
            s = str(binascii.b2a_hex(ser.readline()))  # 读取串口数据
            if s != '':
                data_1 = re.findall(r'7b41.*7d',str(s))[0]
                data = binascii.unhexlify(data_1)
                # data = np.fromstring(data_1, dtype=np.uint8)
                # print(data)
                # data = re.fiBVndall(r'A\d=.*,', str(s),)
                data = str(data).replace("{",'').replace("}", "'").split("'")[1]
                temper_data.put(data)
        except:
            pass

# 建立mqtt连接
def on_connect(client, userdata, flag, rc):
    print("Connect with the result code " + str(rc))     # 订阅内容
    client.subscribe('send8888801', qos=0)  # LED
    client.subscribe('send8888802', qos=0)
    client.subscribe('send8888803', qos=0)  # FAN  风扇
    client.subscribe('send8888804', qos=0) # 门锁

# 接收、处理mqtt消息
def on_message(client, userdata, msg):
    out = str(msg.payload.decode('utf-8'))
    MAC = str(msg.topic).replace('send','')
    # print(msg.topic)
    # print(msg.topic)
    # print(out)
    # 收到消息后执行任务
    if msg.topic ==  'apt-00 12 4B 00 03 D4 42 2F':
        pass
    elif msg.topic == 'send8888801':   #  接受订阅MAC地址
        if out == '1':
            msg_light = 'FE 0C 29 00 02 4E AD 00 00 7B 4F 44 31 3D 31 7D F4'
            ser.write(bytes.fromhex(msg_light))            #  向协调器发送命令
            print('OK')
        elif out == '0':
            msg_light = 'FE 0C 29 00 02 4E AD 00 00 7B 43 44 31 3D 31 7D F8'   #  LED 4E AD
            ser.write(bytes.fromhex(msg_light))  # 向协调器发送命令
            print('OK')
    elif msg.topic == "send8888803":
        if out == '1':
            msg_fx = 'FE 0C 29 00 02 50 7D 00 00 7B 4F 44 31 3D 31 7D 3A'
            ser.write(bytes.fromhex(msg_fx))  # 向协调器发送命令
            print('OK')
        elif out == '0':
            msg_fx = 'FE 0C 29 00 02 50 7D 00 00 7B 43 44 31 3D 31 7D 36'    # 风扇  50 7D
            ser.write(bytes.fromhex(msg_fx))  # 向协调器发送命令
            print('OK')
    elif msg.topic =='send8888804':
        if out == '1':
            msg_lock = 'FE 0C 29 00 02 CC 50 00 00 7B 4F 44 31 3D 31 7D 8B'   # 门锁   CC 50
            ser.write(bytes.fromhex(msg_lock))  # 向协调器发送命令
            print('OK')
    # mqtt客户端启动函数
def mqttfunction():
    global client
    # 使用loop_start 可以避免阻塞Django进程，使用loop_forever()可能会阻塞系统进程
    # client.loop_start()
    # client.loop_forever() 有掉线重连功能
    client.loop_forever(retry_first_connection=True)


client = mqtt.Client(client_id="SHIJIJI", clean_session=False)


def message(MAC, msg, count):
    try:
        if msg != ' ':
            print(msg)
            client.publish(str(8888801), msg)
            print('已成功发送%d条' %count)
    except:
        print('等待加载中···')



# 启动函数
def mqtt_run():
    client.on_connect = on_connect
    client.on_message = on_message
    # 绑定 MQTT 服务器地址
    broker = 'test.ranye-iot.net'
    # MQTT服务器的端口号
    client.connect(broker, 1883, 62)
    # client.username_pw_set('user', 'user')
    client.reconnect_delay_set(min_delay=1, max_delay=2000)
    # 启动
    mqttthread = Thread(target=mqttfunction)
    mqttthread.start()


def get_data():
    MAC = '8888801'
    count = 1
    time.sleep(1)
    while True:
        # MAC = temper_data.get()
        recv = temper_data.get()
        message(MAC,recv,count)
        count += 1



# 启动 MQTT
# mqtt_run()

if __name__ == "__main__":
    # global MAC, recv    p = threading.Thread(target=ser_receive, name='')
    temper_data = Queue(1)
    p = threading.Thread(target=ser_receive, name='')
    c = threading.Thread(target=mqtt_run, name='')
    m=threading.Thread(target=get_data)
    p.start()
    c.start()
    m.start()
